{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "合并完成：1.mp3\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "def download_m3u8(m3u8_url, output):\n",
    "    # 获取 m3u8 文件\n",
    "    res = requests.get(m3u8_url)\n",
    "    res.raise_for_status()\n",
    "    lines = res.text.splitlines()\n",
    "\n",
    "    ts_urls = [line for line in lines if line.endswith(\".ts\")]\n",
    "\n",
    "    with open(output, \"wb\") as f:\n",
    "        for i, ts_url in enumerate(ts_urls, 1):\n",
    "            ts_res = requests.get(ts_url, stream=True)\n",
    "            ts_res.raise_for_status()\n",
    "            for chunk in ts_res.iter_content(chunk_size=8192):\n",
    "                f.write(chunk)\n",
    "            print(f\"已下载 {i}/{len(ts_urls)} 段\")\n",
    "\n",
    "    print(f\"合并完成：{output}\")\n",
    "\n",
    "# 示例：用开源 m3u8 流（公共演示流）\n",
    "m3u8_demo = \"https://ke.renrenjiang.cn/new/#/column?id=177949&aid=9336007\"\n",
    "download_m3u8(m3u8_demo, \"1.mp3\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
